package checkers.client.logic.classes.network;

import java.io.IOException;
import java.net.Socket;

import checkers.client.logic.classes.Logger;
import checkers.common.logic.commands.Command;

public class NetLayer {

	private Logger log;
	private int port;
	private String address;
	private CommandsSerializer serializer;
	private Socket socket;
	
	public NetLayer(Logger log, String address, int port) throws Exception {
		this.log = log;
		this.address = address;
		this.port = port;
		serializer = new CommandsSerializer("checkers.common.logic.commands");
	}

	private void connect() throws IOException {
		socket = new Socket(address, port);
		if (!socket.isConnected()) {
			throw new IOException("Can't connect.");
		} else {
		    
		}
	}
	
	public void sendCommand(Command command) throws Exception {
		connect();
		serializer.writeCommandToStream(socket.getOutputStream(), command);
		socket.shutdownOutput();
		log.addMessage("Command sent: " + command.getClass().toString());
	}
	
	public Command startReceivingCommand() throws Exception {
		Command command = (Command)serializer.getCommandFromStream(socket.getInputStream());
		log.addMessage("Command received: "  + command.getClass().toString());
		return command;
	}
	
}
